/**
 * 
 */
package com.ys.ylideas.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.ylideas.YlIdeasApplication;
import com.ys.ylideas.entity.BaiKeyword;
import com.ys.ylideas.entity.BaiProject;
import com.ys.ylideas.entity.IdeaEntity;
import com.ys.ylideas.entity.UserInfo;
import com.ys.ylideas.model.CreativeTypeResultReport;
import com.ys.ylideas.model.KeyWordTypeResultReport;
import com.ys.ylideas.model.SearchWordTypeResultReport;

/**
 * @author Red
 *
 */
public class HttpRequest {
	private static UserInfo userInfo;
	private static String token = "de86e485832d365067078dda4cd2d2eb";

	/**
	 * 从配置文件中读取
	 */

	public static void setUp() {
		Properties prop = new Properties();
		try {
			prop.load(HttpRequest.class.getClassLoader().getResourceAsStream("baidu-app.properties"));

			userInfo = new UserInfo();
			userInfo.setClientId(prop.getProperty("clientId"));
			userInfo.setClientSecret(prop.getProperty("clientSecret"));
			userInfo.setGrantType(prop.getProperty("grantType"));
			userInfo.setRedirect_uri(prop.getProperty("redirect_uri"));
			userInfo.setUri(prop.getProperty("uri"));

			// System.out.println("HttpRequest:"+userInfo);

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static JSONObject getAccountInfo(String accessToken) {
		String jsonData = "{\"header\":" + "{\"token\": \"" + token + "\"," + "\"accessToken\": \"" + accessToken
				+ "\"}," + "\"body\": {\"accountFields\": [\"userId\",\"cost\"]}}";
		String url = "https://api.baidu.com/json/sms/v4/AccountService/getAccountInfo";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", jsonData);
		return jsonObject;
	}

	// 新增方法
	// 使用refresh_token获取access_token
	// 返回access_token以及新的refresh_token
	public static List<String> getAccessToken(String refresh_token) {
		setUp();
		List<String> list = new ArrayList<>();
		String url = userInfo.getUri() + "?client_id=" + userInfo.getClientId() + "&client_secret="
				+ userInfo.getClientSecret() + "&grant_type=" + "refresh_token" + "&token=" + refresh_token;
		JSONObject jsonObject = new JSONObject();
		jsonObject = GetHttpJsonobject.httpsRequest(url, "POST", null);
		
		if (jsonObject == null) {
			return null;
		}
		CommonData.logger.debug(jsonObject.toString());
		list.add(jsonObject.getString("access_token"));
		list.add(jsonObject.getString("refresh_token"));
		return list;
	}

	public static Map<Long, String> getUserKeywords(String accessToken, HttpSession httpSession) throws Exception {

		Map<Long, String> map1 = new HashMap<>();

		/** 网络请求1：请求推广计划 */
		OtherJsonRequest other = new OtherJsonRequest();
		String jsonData = other.getCampaign(accessToken);
		String url = "https://api.baidu.com/json/sms/v4/CampaignService/getCampaign";
		JSONObject campaign = GetHttpJsonobject.httpsRequest(url, "GET", jsonData);

		String campaignBody = campaign.getString("body");
		String campaignData = JSONObject.parseObject(campaignBody).getString("data");
		JSONArray datas = JSONArray.parseArray(campaignData);
		// String camId = "";
		List<Long> campaignId = new ArrayList<>();
		for (int i = 0; i < datas.size(); i++) {
			JSONObject data = datas.getJSONObject(i);
			map1.put(data.getLong("campaignId"), data.getString("campaignName"));
			campaignId.add(data.getLong("campaignId"));
		}
		Long[] ids = new Long[campaignId.size()];
		campaignId.toArray(ids);
		Thread getThread = new Thread() {
			Map<Long, List<Map<Long, String>>> map4 = new HashMap<>();
			Map<Long, List<Map<Long, String>>> map5 = new HashMap<>();

			@Override
			public void run() {
				// TODO Auto-generated method stub
				super.run();
				/** 网络请求2：请求推广单元 */
				String jsonData2 = other.getAdgroup(accessToken, ids);
				String url2 = "https://api.baidu.com/json/sms/v4/AdgroupService/getAdgroup";
				JSONObject adgroup = GetHttpJsonobject.httpsRequest(url2, "GET", jsonData2);

				String adgroupBody = adgroup.getString("body");
				String adgroupData = JSONObject.parseObject(adgroupBody).getString("data");
				JSONArray unitDatas = JSONArray.parseArray(adgroupData);
				List<Long> AdgroupId = new ArrayList<>();
				for (int a = 0; a < unitDatas.size(); a++) {
					JSONObject data2 = unitDatas.getJSONObject(a);
					Map<Long, String> map2 = new HashMap<>();
					map2.put(data2.getLong("adgroupId"), data2.getString("adgroupName"));
					if (map4.get(data2.getLong("campaignId")) != null) {
						map4.get(data2.getLong("campaignId")).add(map2);
					} else {
						List<Map<Long, String>> camAdgList = new ArrayList<>();
						camAdgList.add(map2);
						map4.put(data2.getLong("campaignId"), camAdgList);
					}
					AdgroupId.add(data2.getLong("adgroupId"));
				}
				httpSession.setAttribute("camAdgMap", map4);
				Long[] lds = new Long[AdgroupId.size()];
				AdgroupId.toArray(lds);
				/** 网络请求3：请求推广词 */
				String jsonData3 = other.getWord(accessToken, lds);
				String url3 = "https://api.baidu.com/json/sms/v4/KeywordService/getWord";
				JSONObject keyword = GetHttpJsonobject.httpsRequest(url3, "GET", jsonData3);

				String keywordBody = keyword.getString("body");
				String keywordData = JSONObject.parseObject(keywordBody).getString("data");
				JSONArray keyDatas = JSONArray.parseArray(keywordData);

				for (int b = 0; b < keyDatas.size(); b++) {
					JSONObject data3 = keyDatas.getJSONObject(b);
					Map<Long, String> map3 = new HashMap<>();
					map3.put(data3.getLong("keywordId"), data3.getString("keyword"));
					if (map5.get(data3.getLong("adgroupId")) != null) {
						map5.get(data3.getLong("adgroupId")).add(map3);
					} else {
						List<Map<Long, String>> adgKyList = new ArrayList<>();
						adgKyList.add(map3);
						map5.put(data3.getLong("adgroupId"), adgKyList);
					}
				}
				httpSession.setAttribute("adgKyMap", map5);
			}
		};
		getThread.start();
		return map1;
	}

	// 增加创意
	public static Map<String, Object> addCreate(String accessToken, IdeaEntity ideas) {
		CreativeJsonRequest cj = new CreativeJsonRequest();
		String data = cj.addOrUpdate(accessToken, ideas, 0);
		// System.out.println(data);
		String url = "https://api.baidu.com/json/sms/v4/CreativeService/addCreative";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);

		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			// System.out.println("failure");
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			String code = res.getString("code");
			map.put("status", "failure");
			map.put("code", code);
			map.put("msg", msg);
		} else if (desc.equals("success")) {
			// System.out.println("success");
			JSONObject body = jsonObject.getJSONObject("body");
			JSONArray createData = body.getJSONArray("data");
			JSONObject onlyData = createData.getJSONObject(0);
			long creativeId = onlyData.getLongValue("creativeId");
			map.put("status", "success");
			map.put("creativeId", creativeId);
		} else {
			CommonData.logger.error(jsonObject.toString());
		}
		return map;
	}

	// 修改创意
	public static Map<String, Object> updateCreate(String accessToken, IdeaEntity ideas) {
		CreativeJsonRequest cj = new CreativeJsonRequest();
		String data = cj.addOrUpdate(accessToken, ideas, 1);
		String url = "https://api.baidu.com/json/sms/v4/CreativeService/updateCreative";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);

		// 返回一个修改的结果
		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			String code = res.getString("code");
			map.put("status", "failure");
			map.put("code", code);
			map.put("msg", msg);
		} else if (desc.equals("success")) {
			map.put("status", "success");
		} else {
			CommonData.logger.info(jsonObject.toString());
		}
		return map;
	}

	// 删除创意
	public static Map<String, Object> deleteCreate(String accessToken, Long[] ids) {
		CreativeJsonRequest cj = new CreativeJsonRequest();
		String data = cj.delete(accessToken, ids);
		String url = "https://api.baidu.com/json/sms/v4/CreativeService/deleteCreative";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);

		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String code = res.getString("code");
			map.put("status", "failure");
			map.put("code", code);
		} else if (desc.equals("success")) {
			map.put("status", "success");
		} else {
			CommonData.logger.info(jsonObject.toString());
			JSONArray failures = header.getJSONArray("failures");
			// success code
			List<Integer> suCode = new ArrayList<>();
			// fail code
			List<Integer> failCode = new ArrayList<>();

			for (int i = 0; i < ids.length; i++) {
				suCode.add(i);
			}
			Collections.reverse(suCode);
			for (int j = failures.size() - 1; j >= 0; j--) {
				JSONObject fail = failures.getJSONObject(j);
				String pos = fail.getString("position");
				int index = StringDealUtil.getInnerWord(pos);
				failCode.add(index);
				suCode.remove(index);
			}

			map.put("status", "some fail,some success");
			map.put("suCode", suCode);
			map.put("failCode", failCode);
		}
		return map;
	}

	// 获取创意
	public static Map<String, Object> getCreate(String accessToken, Long[] ids) {
		CreativeJsonRequest cj = new CreativeJsonRequest();
		String data = cj.get(accessToken, ids);

		String url = "https://api.baidu.com/json/sms/v4/CreativeService/getCreative";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);
		// System.out.println(jsonObject);
		// 返回一个创意列表
		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			// System.out.println("failure");
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			map.put("status", "failure");
			map.put("reason", msg);
		} else if (desc.equals("success")) {
			// System.out.println("success");
			JSONObject body = jsonObject.getJSONObject("body");
			JSONArray createData = body.getJSONArray("data");
			List<IdeaEntity> ideas = new ArrayList<>();
			for (int i = 0; i < createData.size(); i++) {
				JSONObject onlyData = createData.getJSONObject(i);
				IdeaEntity idea = new IdeaEntity();
				idea.setAdgroupId(onlyData.getLongValue("adgroupId"));
				idea.setCreativeId(onlyData.getLongValue("creativeId"));
				idea.setDevicePerference(onlyData.getIntValue("devicePreference"));
				idea.setDisplayUrl(onlyData.getString("pcDisplayUrl"));
				idea.setVisitUrl(onlyData.getString("pcDestinationUrl"));
				idea.setMobileDisplayUrl(onlyData.getString("mobileDisplayUrl"));
				idea.setMobileVisitUrl(onlyData.getString("mobileDestinationUrl"));
				idea.setPause(onlyData.getBooleanValue("pause"));
				idea.setIdeaTitle(onlyData.getString("title"));
				idea.setIdeaDesOne(onlyData.getString("description1"));
				idea.setIdeaDesTwo(onlyData.getString("description2"));
				ideas.add(idea);
			}
			map.put("status", "success");
			map.put("data", ideas);
		} else {
			CommonData.logger.error(jsonObject.toString());
		}
		return map;
	}
	
	
	// 获取关键词报告
	public static Map<String, Object> getKeyWordReport(String accessToken,Long userId) {
		ReportJson rj = new ReportJson();
		String data = rj.getKeyReportJson(accessToken);

		String url = "https://api.baidu.com/json/sms/v4/ReportService/getRealTimeData";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);
		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			map.put("status", "failure");
			map.put("reason", msg);
			CommonData.logger.debug(msg);
		} else if (desc.equals("success")) {
			// System.out.println("success");
			JSONObject body = jsonObject.getJSONObject("body");
			JSONArray createData = body.getJSONArray("data");
			List<KeyWordTypeResultReport> ktrrList = new ArrayList<>();
			for (int i = 0; i < createData.size(); i++) {
				JSONObject onlyData = createData.getJSONObject(i);
				KeyWordTypeResultReport ktReport = new KeyWordTypeResultReport();
				JSONArray name = onlyData.getJSONArray("name");
				JSONArray kpis = onlyData.getJSONArray("kpis");
				ktReport.setUserId(userId);
				ktReport.setImportDate(new Date());
				ktReport.setAccountName(name.getString(0));
				ktReport.setCampaignName(name.getString(1));
				ktReport.setAdgroupName(name.getString(2));
				ktReport.setKeyword(name.getString(3));
				ktReport.setImpression(kpis.getInteger(0));
				ktReport.setClick(kpis.getInteger(1));
				ktReport.setCost(kpis.getDouble(2));
				if(!"-".equals(kpis.getString(3)))
					ktReport.setAvgPosition(kpis.getDouble(3));
				ktReport.setCtr(kpis.getDouble(4));
				ktReport.setCpc(kpis.getDouble(5));
				ktReport.setCpm(kpis.getDouble(6));
				ktReport.setConversion(kpis.getDouble(7));
				ktReport.setBridgeConversion(kpis.getDouble(8));
				ktrrList.add(ktReport);
			}
			map.put("status", "success");
			map.put("ktrrList", ktrrList);
		} else {
			CommonData.logger.error(jsonObject.toString());
		}
		return map;
	}

	// 获取搜索词报告
	public static Map<String, Object> getSearchWordReport(String accessToken,Long userId) {
		// TODO Auto-generated method stub
		ReportJson rj = new ReportJson();
		String data = rj.getSearchwordReportJson(accessToken);

		String url = "https://api.baidu.com/json/sms/v4/ReportService/getRealTimeQueryData";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);
		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			map.put("status", "failure");
			map.put("reason", msg);
			CommonData.logger.debug(msg);
		} else if (desc.equals("success")) {
			// System.out.println("success");
			JSONObject body = jsonObject.getJSONObject("body");
			JSONArray createData = body.getJSONArray("data");
			List<SearchWordTypeResultReport> swtrList = new ArrayList<>();
			for (int i = 0; i < createData.size(); i++) {
				JSONObject onlyData = createData.getJSONObject(i);
				SearchWordTypeResultReport swtrr = new SearchWordTypeResultReport();
				JSONArray queryInfo = onlyData.getJSONArray("queryInfo");
				JSONArray kpis = onlyData.getJSONArray("kpis");
				swtrr.setUserId(userId);
				swtrr.setImportDate(new Date());
				swtrr.setQuery(onlyData.getString("query"));
				swtrr.setKeywordId(onlyData.getLong("keywordId"));
				swtrr.setCreativeId(onlyData.getLong("creativeId"));
				swtrr.setAccountName(queryInfo.getString(0));
				swtrr.setCampaignName(queryInfo.getString(1));
				swtrr.setAdgroupName(queryInfo.getString(2));
				swtrr.setKeyword(queryInfo.getString(3));
				swtrr.setCreativeTitle(queryInfo.getString(4));
				swtrr.setCreativeDesOne(queryInfo.getString(5));
				swtrr.setCreativeDesTwo(queryInfo.getString(6));
				swtrr.setCreativeDisplayUrl(queryInfo.getString(7));
				swtrr.setSearchEngine(queryInfo.getString(8));
				if(!"-".equals(queryInfo.getString(9)))
					swtrr.setExactMatch(queryInfo.getString(9));
				swtrr.setImpression(kpis.getInteger(0));
				swtrr.setClick(kpis.getInteger(1));
				swtrr.setCost(kpis.getDouble(2));
				swtrr.setCtr(kpis.getDouble(3));
				swtrList.add(swtrr);
			}
			map.put("status", "success");
			map.put("swtrList", swtrList);
		} else {
			CommonData.logger.error(jsonObject.toString());
		}
		return map;
	}
	// 获取创意报告
	public static Map<String, Object> getCreativeReport(String accessToken,Long userId) {
		// TODO Auto-generated method stub
		ReportJson rj = new ReportJson();
		String data = rj.getCreativeReportJson(accessToken);

		String url = "https://api.baidu.com/json/sms/v4/ReportService/getRealTimeData";
		JSONObject jsonObject = GetHttpJsonobject.httpsRequest(url, "GET", data);
		Map<String, Object> map = new HashMap<>();
		JSONObject header = jsonObject.getJSONObject("header");
		String desc = header.getString("desc");
		if (desc.equals("failure")) {
			JSONArray failures = header.getJSONArray("failures");
			JSONObject res = failures.getJSONObject(0);
			String msg = res.getString("message");
			map.put("status", "failure");
			map.put("reason", msg);
			CommonData.logger.debug(msg);
		} else if (desc.equals("success")) {
			// System.out.println("success");
			JSONObject body = jsonObject.getJSONObject("body");
			JSONArray createData = body.getJSONArray("data");
			List<CreativeTypeResultReport> ctrrList = new ArrayList<>();
			for (int i = 0; i < createData.size(); i++) {
				JSONObject onlyData = createData.getJSONObject(i);
				CreativeTypeResultReport ctrr = new CreativeTypeResultReport();
				JSONArray name = onlyData.getJSONArray("name");
				JSONArray kpis = onlyData.getJSONArray("kpis");
				ctrr.setUserId(userId);
				ctrr.setImportDate(new Date());
				ctrr.setAccountName(name.getString(0));
				ctrr.setCampaignName(name.getString(1));
				ctrr.setAdgroupName(name.getString(2));
				ctrr.setCreativeTitle(name.getString(3));
				ctrr.setCreativeDesOne(name.getString(4));
				ctrr.setCreativeDesTwo(name.getString(5));
				ctrr.setCreativeDisplayUrl(name.getString(6));
				
				ctrr.setImpression(kpis.getInteger(0));
				ctrr.setClick(kpis.getInteger(1));
				ctrr.setCost(kpis.getDouble(2));
				if(!"-".equals(kpis.getString(3)))
					ctrr.setAvgPosition(kpis.getDouble(3));
				ctrr.setCtr(kpis.getDouble(4));
				ctrr.setCpc(kpis.getDouble(5));
				ctrr.setCpm(kpis.getDouble(6));
				ctrr.setConversion(kpis.getDouble(7));
				ctrr.setBridgeConversion(kpis.getDouble(8));
				ctrrList.add(ctrr);
			}
			map.put("status", "success");
			map.put("ctrrList", ctrrList);
		} else {
			CommonData.logger.error(jsonObject.toString());
		}
		return map;
	}
	
	
	
	
	
}
